const db = uniCloud.database()
const indentDB = db.collection('dish-order-form')
const orderFormDB = db.collection('dish-order-form')
const mapTmplId = {
	orderSuccess: 'uo7jdEa8dcocHYewvo6way0jVzpBkT4Z8Hrx5KgvoMM',
	approve: 'Q0nQCGwQob36aGkr8hMT0lquJ8ACqHumW3g5b-CE5oA'
	// indentCancel: 'mIzEx7pXKxkcPaOtUvQTRKv0hRoztL32A1_9keRnhB0'
}
export default {
	state: {
		mapScrollTop: [],
		dataList: null,
		sideActiveKey: 0,
		roomList: {},
		specificationList: [],
		selectedRooms: [],
		roomCheckedByID: [],
		region: "苏州",
		mapIndentStatus: {
			"0": "待提交",
			"1": "审核中",
			"2": "待制作",
			"3": "已完成",
			"-1": "已取消",
			"-2": "不通过",
		},
		shareIndent: null,
		shareOrderTimer: null
	},
	getters: {
		shoppingCart(state) {
			const shoppingCart = state.dataList?.flatMap(e => e[1])?.filter(e => e.num) || []
			const list = Array.from(new Set(shoppingCart)).concat(state.specificationList)
			console.log(list);
			return list
		},
		totalpPrice(state, getter) {
			return getter.shoppingCart.reduce((price, it) => ((price += it.price * it.num), price), 0).toFixed(2)
		},
		handledRoomList(state) {
			const roomList = Object.entries(state.roomList)
			const cur = Object.values(state.roomList).flat().find(e => e._id === state.roomCheckedByID[0])
			return roomList.map(e => ({
				text: e[0],
				children: e[1].map(e => ({
					...e, 
					disabled: cur ? e.place_type !== cur.place_type : false, 
					checked: state.roomCheckedByID.includes(e._id),
				}))
			}))
		},
	},
	mutations: {
		setMapScrollTop(state, data) {
			state.mapScrollTop = data
		},
		setSideActiveKey(state, data) {
			state.sideActiveKey = data
		},
		setDataList(state, data) {
			state.dataList = data
		},
		setSpecificationList(state, [goods, num]) {
			const result = state.specificationList.find(e => e._id === goods._id && e.specificationSelected.toString() === goods.specificationSelected.toString())
			if (result) {
				result.num += num
			} else {
				goods.num = num
				state.specificationList.push(goods)
			}
			state.specificationList = state.specificationList.filter(e => e.num)
		},
		setRegion(state, data) {
			state.region = data
			uni.setStorageSync('region', state.region)
		},
		changeGoodsNum(state, [index, i, num]) {
			const item = state.dataList[index][1][i]
			item.num += num
		},
		changeGoodsNumByGoods(state, [num, goods]) {
			goods.num += num
		},
		changeGoodsNumByID(state, [id, num]) {
			const res = state.dataList?.flatMap(e => e[1])?.find(e => e._id === id)
			if (res) res.num += num
		},
		clearShoppingCart(state, shoppingCart) {
			shoppingCart.forEach(e => e.num = 0)
			state.specificationList = []
		},
		setRoomList(state, data) {
			state.roomList = {...state.roomList, ...data}
		},
		setSelectedRooms(state, data) {
			state.selectedRooms = data
		},
		setRoomCheckedByID(state, data) {
			state.roomCheckedByID = data
		},
		setShareOrderTimer(state, data) {
			state.shareOrderTimer = data
		}, 
		setShareIndent(state, data) {
			state.shareIndent = data
		}
	},
	actions: {
		async requestRoomList({commit}) {
			try{
				const arr = ['苏州', '温州']
				const l = arr.map(e => db.collection('dish-dining-place').where(`"${e}" in region`).orderBy('sort asc').get().then(res => res.result.data))
				const [su, wen] = await Promise.allSettled(l)
				commit('setRoomList', {
					'苏州': su.value || [],
					'温州': wen.value || []
				})
			}catch(e){
				//TODO handle the exception
				uni.showModal({
				  content: err.message || '请求服务失败',
				  showCancel: false
				})
			}
		},
		async subscriptionMsg(store, indent_id) {
			console.log(indent_id);
			const orderFormTemp = orderFormDB.where({_id: indent_id}).getTemp()
			const res = await db.collection(orderFormTemp, 'dish-dining-place').get()
			const indent = res.result.data[0]
			const dining_place = indent.dining_place[0].name
			const ressss = await uniCloud.callFunction({
				name: 'send-subscription-msg',
				data: {
					template_id: mapTmplId.orderSuccess,
					page: '/pages/indent-detail/indent-detail?id=' + indent_id,
					touser: indent.user_id,
					data: {
						character_string3: {value: indent.order_form_queue},
						phrase5: {value: '审核中'},
						thing6: {value: `${dining_place}${indent.dining_place.length > 1 ? ' 等' : ''}`},
						date8: {value: indent.dining_date[0]},
						thing11: {value: indent.dining_person_num},
					}
				}
			})
			console.log('订阅结果', ressss);
		},
		async submitShareIndent({dispatch}, indent_id) {
			uni.showModal({
				title: '提示',
				content: '你确定提交订单吗',
				success: async () => {
					const tmplIds = Object.values(mapTmplId)
					wx.requestSubscribeMessage({
						tmplIds,
						success: async (res) => {
							console.log('requestSubscribeMessage res', res);
							const subscriptionOrder = res[mapTmplId.orderSuccess] === 'accept';
							subscriptionOrder && await dispatch('subscriptionMsg', indent_id)
						},
						fail: (err) => {
							console.log('requestSubscribeMessage err', err);
						},
						complete: async () => {
							await indentDB.doc(indent_id).update({
								status: 1
							})
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
							uni.$emit('refreshIndentList')
						}
					})
					
				}
			})
		},
	}
}